﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DBLibrary;
using System.Text;

public partial class masterPages_customer_AddNewMember : System.Web.UI.Page
{
    /// <summary>
    /// a <=> add
    /// m <=> modify
    /// </summary>
    private string mActionString = "a";
    private long mCustomerId = -1;
    protected string[] mExistExtNames;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(this.Request.QueryString["action"]))
        {
            mActionString = this.Request.QueryString["action"];
        }
        if (mActionString.Equals("m", StringComparison.OrdinalIgnoreCase))
        {
            mCustomerId = long.Parse(this.Request.QueryString["id"]);
            CustomerDetail cd = PoseidonDBHelper.UserDB.Select<CustomerDetail>(new DBParam("CustomerId", mCustomerId))[0];
            this.CustomerNameTextBox.Text = cd.Name;
            this.EmailTextBox.Text = cd.EMail;
            this.PhoneTextBox.Text = cd.Phone;
            this.LevelDropDownList.SelectedIndex = cd.Level - 1;
            if (cd.Gender.Equals("男"))
            {
                this.GenderDropDownList.SelectedIndex = 0;
            }
            else
            {
                this.GenderDropDownList.SelectedIndex = 1;
            }

            List<CustomerExtendKeyValue> list = CustomerExtendFieldHelper.GetCustomerDetailInfos(mCustomerId);
            if (list != null)
            {
                StringBuilder sb = new StringBuilder();
                string names = string.Empty;
                for (int i = 0; i < list.Count; i++)
                {
                    CustomerExtendKeyValue kv = list[i];
                    sb.Append("<tr><td align=\"center\">");
                    sb.Append(kv.ExtName);
                    sb.Append("</td><td>");
                    sb.Append("<input type=\"text\" value=\"");
                    sb.Append(kv.ExtValue.ToString());
                    sb.Append("\" r=\"");
                    sb.Append(kv.Row);
                    sb.Append("\" f=\"");
                    sb.Append(kv.ExtField);
                    sb.Append("\"></input>");

                    sb.AppendLine("</td></tr>");
                    if (i == list.Count - 1)
                    {
                        names += Server.HtmlEncode(kv.ExtName);
                    }
                    else
                    {
                        names += Server.HtmlEncode(kv.ExtName) + "#%@%#";
                    }
                }
                existNames.Value = names;
                extDetail.InnerHtml = sb.ToString();
            }
        }
    }

    protected void AddImageButton_Click(object sender, ImageClickEventArgs e)
    {
        DB db = PoseidonDBHelper.UserDB;
        CustomerDetail cd = null;
        if (mActionString.Equals("m", StringComparison.OrdinalIgnoreCase))
        {
            cd = db.Select<CustomerDetail>(new DBParam("CustomerId", mCustomerId))[0];
        }
        else
        {
            cd = new CustomerDetail();
        }
        cd.Name = CustomerNameTextBox.Text;
        cd.EMail = EmailTextBox.Text;
        cd.Gender = GenderDropDownList.SelectedValue;
        cd.Level = int.Parse(LevelDropDownList.SelectedValue);
        cd.Phone = PhoneTextBox.Text;
        long tempId = -1;
        if (mActionString.Equals("m", StringComparison.OrdinalIgnoreCase))
        {
            db.Update(cd, "CustomerId");
            tempId = mCustomerId;
        }
        else
        {
            db.Insert(cd, out tempId);
        }

        List<CustomerExtendKeyValue> extList = new List<CustomerExtendKeyValue>();
        if (!string.IsNullOrEmpty(cusExtHidden.Value))
        {
            string newExtValue = cusExtHidden.Value;
            string[] exts = newExtValue.Split(new string[] { "#%@%#" }, StringSplitOptions.None);
            for (int i = 0; i < exts.Length; i = i + 2)
            {
                CustomerExtendKeyValue kv = new CustomerExtendKeyValue();
                kv.ExtField = string.Empty;
                kv.ExtName = Server.HtmlDecode(exts[i]);
                kv.ExtValue = Server.HtmlDecode(exts[i + 1]);
                kv.Row = -1;
                extList.Add(kv);
            }
        }

        if (!string.IsNullOrEmpty(extDetail.InnerHtml))
        {
            string xmlStr = "<Root>" + extDetail.InnerHtml + "</Root>";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlStr);
            foreach (XmlElement trEl in doc.DocumentElement.ChildNodes)
            {
                CustomerExtendKeyValue kv = new CustomerExtendKeyValue();
                XmlNodeList clist = trEl.GetElementsByTagName("td");
                kv.ExtName = clist[0].InnerText;
                kv.ExtValue = clist[1].ChildNodes[0].Attributes["value"].Value;
                if (mActionString.Equals("m", StringComparison.OrdinalIgnoreCase))
                {
                    kv.Row = int.Parse(clist[1].ChildNodes[0].Attributes["r"].Value);
                    kv.ExtField = clist[1].ChildNodes[0].Attributes["f"].Value;
                }
                else
                {
                    kv.Row = -1;
                    kv.ExtField = string.Empty;
                }
                extList.Add(kv);
            }
        }
        CustomerExtendFieldHelper.UpdateOrInsertCustomerDetailInfos(tempId, extList);

        this.Response.Redirect("~/pages/member/MemberOperation.aspx");
    }
}